package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.SheetListContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.UsedAdapter
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.SheetModel
import fm.dongman.presenterlib.presenter.SheetListPresenter
import kotlinx.android.synthetic.main.fragment_sheet_list.*
import kotlinx.android.synthetic.main.item_sheet_list.view.*
import org.jetbrains.anko.onClick

/**
 * 漫单列表页面
 * Created by shize on 2017/11/5.
 */
class LabelSheetListFragment : BaseFragment(), SheetListContract.ISheetListView {
    private var mPresenter: SheetListContract.ISheetListPresenter? = null // 全局数据控制器
    private var mFlagType: String = TYPE_SEARCH // 类型
    private var mFlagId: String = "" // 关键字 or id
    private var mFlagName: String = "专题类型"

    private lateinit var mScrollListener: LoadMoreRecyclerOnScrollListener // 滑动监听器

    private lateinit var mSheetListAdapter: SheetListAdapter // 漫单列表适配器
    private val mSheetList: ArrayList<IModel.ISheetModel> = ArrayList() // 漫单数据集合

    private lateinit var mFooterView: View // 列表底部 View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_sheet_list, container, false)
        SheetListPresenter(this, Injection.provideSheetListRepository())
        return view
    }

    override fun setNewParam(key: String) {
        mFlagId = key
        requestListData(1)
    }

    override fun requestListData(page: Int) {
        mPresenter?.getSheets(page, mFlagType, mFlagId)
        mScrollListener.clearPage()
        mSheetListAdapter.addFooterView(mFooterView)
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun initData() {
        if (arguments != null) {
            mFlagName = arguments.getString(FLAG_NAME)
            mFlagId = arguments.getString(FLAG_ID)
        }
    }

    override fun bindData() {
        bindToolbar()
        bindSheetList()
    }

    private fun bindToolbar() {
        mSheetListToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mSheetListToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
        mSheetListToolbar.title = mFlagName
    }

    @SuppressLint("InflateParams")
    private fun bindSheetList() {
        mFooterView = LayoutInflater.from(activity).inflate(R.layout.layout_loading, null)
        mSheetListAdapter = SheetListAdapter(activity, mSheetList)
        mSheetListRecycler.adapter = mSheetListAdapter
        mSheetListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mSheetListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                mPresenter?.getSheets(currentPage, mFlagType, mFlagId)
            }
        }
        mSheetListRecycler.addOnScrollListener(mScrollListener)
        requestListData(1)
    }

    override fun setPresenter(presenter: SheetListContract.ISheetListPresenter) {
        mPresenter = presenter
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError(getString(R.string.str_refresh_failed))
        onStateChanged(MultiStateLayout.EMPTY)
    }

    override fun showSearchTopicResult(topics: List<IModel.ISheetModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mSheetList.clear()
        mSheetList.addAll(topics)
        mSheetListAdapter.notifyDataSetChanged()
        if (topics.size < 10) {
            // 加载完毕
            mSheetListAdapter.removeFooterView()
        }

    }

    override fun showMoreSearchTopicResult(topics: List<IModel.ISheetModel>) {
        if (topics.isEmpty()) {
            mSheetListAdapter.removeFooterView()
            return
        }
        mSheetList.addAll(topics)
        mSheetListAdapter.notifyDataSetChanged()
    }

    override fun showSheets(sheets: List<IModel.ISheetModel>) {}

    override fun showMoreSheets(sheets: List<IModel.ISheetModel>) {}

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    override fun showDeleteState(boolean: Boolean) {}

    /**
     * 切换状态
     */
    private fun onStateChanged(state: Int) {
        mSheetListMultiState?.changeState(state)
    }

    companion object {
        private val FLAG_NAME = "fm.dongman.animefm.sheetList.flagName" // 类型名
        private val FLAG_ID = "fm.dongman.animefm.sheetList.flagId" // id key

        val TYPE_SEARCH = SheetListContract.ISheetListPresenter.TYPE_SEARCH // 搜索

        /**
         * 获取实例
         */
        fun getInstance(flagType: String, flagId: String?): LabelSheetListFragment {
            val bundle = Bundle()
            bundle.putString(FLAG_NAME, flagType)
            bundle.putString(FLAG_ID, flagId)
            val fragment = LabelSheetListFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    /**
     * 漫单列表适配器
     */
    private class SheetListAdapter(private val mContext: Context, private val mData: List<IModel.ISheetModel>)
        : UsedAdapter<SheetListAdapter.SheetListViewHolder>() {
        @SuppressLint("InflateParams")
        override fun onCreateVH(): SheetListViewHolder =
                SheetListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_sheet_list, null))

        override fun onBindVH(holder: SheetListViewHolder, position: Int) {
            val sheet = mData[position] as SheetModel
            holder.mDate.text = sheet.createTime

            holder.itemView.onClick {
                val intent = Intent(mContext, SingleActivity::class.java)
                intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_INFO)
                intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, sheet.mandanId)
                ActivityHelper.startActivity(mContext as Activity, intent)
            }

            holder.mTitle.text = sheet.mandanTitle
            Glide.with(mContext).load(sheet.mandanImg)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 2))
                    .into(holder.mCover)
        }

        override fun getDataTotal(): Int = mData.size

        private class SheetListViewHolder(itemView: View) : UsedViewHolder(itemView) {
            var mTitle: TextView = itemView.mTvSheetListTitle
            var mDate: TextView = itemView.mTvSheetListDate
            var mCover: ImageView = itemView.mIvSheetListCover
        }
    }
}